import { sendSmsCode } from "../../api/auth";

Component({
  properties: {
    phone: {
      type: String,
      value: "",
    },
    code: {
      type: String,
      value: "",
    },
  },

  data: {
    phoneError: false,
    sendCodeText: "发送验证码",
    sending: false,
    countdown: 60,
  },

  methods: {
    _emitChange() {
      this.triggerEvent("change", {
        phone: this.data.phone,
        code: this.data.code,
        phoneError: this.data.phoneError,
      });
    },

    onPhoneChange(e) {
      const { value } = e.detail;
      const isPhoneNumber = /^[1][3,4,5,7,8,9][0-9]{9}$/.test(value);
      this.setData({
        phone: value,
        phoneError: value.length > 0 && !isPhoneNumber,
      });
      this._emitChange();
    },

    onCodeChange(e) {
      this.setData({ code: e.detail.value });
      this._emitChange();
    },

    async sendCode() {
      if (this.data.sending) return;

      const phoneNumber = this.data.phone;

      if (!phoneNumber) {
        wx.showToast({ title: "请输入手机号", icon: "none" });
        return;
      }
      if (this.data.phoneError) {
        wx.showToast({ title: "手机号格式不正确", icon: "none" });
        return;
      }

      const res = await sendSmsCode(phoneNumber);

      if (res.error) {
        wx.showToast({
          title: "发送失败",
          icon: "none",
          // duration: 2000,
        });
        return;
      }

      wx.showToast({
        title: "验证码已发送",
      });

      // const mockCode = Math.floor(100000 + Math.random() * 900000).toString();
      // this.setData({ mockCode });
      // console.log(`模拟验证码已发送: ${mockCode}`);
      // wx.showToast({
      //   title: `验证码: ${mockCode} (仅为测试)`,
      //   icon: "none",
      //   duration: 2000,
      // });

      this.setData({ sending: true, sendCodeText: `${this.data.countdown}s` });

      const timer = setInterval(() => {
        const newCountdown = this.data.countdown - 1;
        if (newCountdown === 0) {
          clearInterval(timer);
          this.setData({
            sendCodeText: "重新发送",
            sending: false,
            countdown: 60,
          });
        } else {
          this.setData({
            countdown: newCountdown,
            sendCodeText: `${newCountdown}s`,
          });
        }
      }, 1000);
    },
  },
});
